#ifndef TGZ_EXTRACTOR_H
#define TGZ_EXTRACTOR_H

#include <string>
#include <iostream>
#include <cstdlib>
#include <sys/stat.h>
#include <unistd.h>
#include <sstream>

class TgzExtractor {
private:
    std::string extract_cmd;
    
    // 检查文件是否存在
    bool file_exists(const std::string& path) {
        struct stat buffer;
        return (stat(path.c_str(), &buffer) == 0);
    }
    
    // 创建目录（如果不存在）
    bool create_directory(const std::string& path) {
        std::string command = "mkdir -p \"" + path + "\"";
        return system(command.c_str()) == 0;
    }

public:
    // 构造函数
    TgzExtractor(std::string _extract_cmd) 
        : extract_cmd(_extract_cmd){}
    
    // 解压函数
    bool extract(const std::string& tgz_path, const std::string& dest_path = "./") {
        // 检查tgz文件是否存在
        if (!file_exists(tgz_path)) {
            std::cerr << "Error: TGZ file does not exist: " << tgz_path << std::endl;
            return false;
        }
        
        // 创建目标目录
        if (!create_directory(dest_path)) {
            std::cerr << "Error: Failed to create extract directory: " << dest_path << std::endl;
            return false;
        }
        
        // 构建tar解压命令
        std::ostringstream command;
        command << extract_cmd << " " << tgz_path << " -C " << dest_path << " 2>/dev/null";
        
        // 执行解压命令
        int result = system(command.str().c_str());
        
        if (result == 0) {
            std::cout << "Successfully extracted: " << tgz_path 
                      << " to " << dest_path << std::endl;
            return true;
        } else {
            std::cerr << "Error: Failed to extract " << tgz_path 
                      << " (exit code: " << result << ")" << std::endl;
            return false;
        }
    }
};

#endif // TGZ_EXTRACTOR_H